#!/bin/bash

set -e
set -x

bypy download mariadb-10.5.27-linux-systemd-x86_64.tar.gz

iplist_path=config
i=1
while read -r line
do
    case $line in
        *'#'*)
            continue
        ;;
        *'end'*)
            break
        ;;
        *)
            IFS=',' read -ra parts <<< "$line"
        ;;
    esac

    pass="${parts[0]}"
    address="${parts[1]}"
    hostname="${parts[2]}"
    flag="${parts[3]}"

    if [ $address ];then
        sshpass -p$pass scp mariadb-10.5.27-linux-systemd-x86_64.tar.gz $address:/opt/
        sshpass -p$pass ssh -n $address tar xf /opt/mariadb-10.5.27-linux-systemd-x86_64.tar.gz -C /usr/local/
        sshpass -p$pass ssh -n $address mv /usr/local/mariadb-10.5.27-linux-systemd-x86_64 /usr/local/mysql
        sshpass -p$pass ssh -n $address useradd -M -s /sbin/nologin  mysql
        sshpass -p$pass ssh -n $address mkdir -p /usr/local/mysql/data/tmp
        sshpass -p$pass ssh -n $address mkdir -p /var/lib/mysql/
        sshpass -p$pass ssh -n $address mkdir -p /var/log/mysql/
        sshpass -p$pass ssh -n $address chown -R mysql:mysql /usr/local/mysql
        sshpass -p$pass ssh -n $address chown -R mysql:mysql /var/lib/mysql
        sshpass -p$pass ssh -n $address chown -R mysql:mysql /var/log/mysql
        sshpass -p$pass ssh -n $address /usr/local/mysql/scripts/mysql_install_db -u mysql --ldata=/usr/local/mysql/data/
        \cp ./two/my.cnf.tpl ./two/my.cnf
        sed -i "s/(server_id)/$i/" ./two/my.cnf
        sshpass -p$pass scp ./two/my.cnf $address:/etc/
        sshpass -p$pass ssh -n $address cp /usr/local/mysql/support-files/systemd/mariadb.service /usr/lib/systemd/system/
        sshpass -p$pass ssh -n $address systemctl daemon-reload
        sshpass -p$pass ssh -n $address systemctl start mariadb.service
        sshpass -p$pass ssh -n $address ln -fs /usr/local/mysql/bin/mysql /usr/bin/
        sshpass -p$pass ssh -n $address yum install -y ncurses-compat-libs
        sshpass -p$pass ssh -n $address sleep 5
        sshpass -p$pass scp init.sql $address:/usr/local/mysql/
        sshpass -p$pass ssh -n $address 'mysql < /usr/local/mysql/init.sql'
        let i=i+1

    fi
done < $iplist_path

sh user.sh
sh start.sh

set +x
set +e